package com.github.binarywang.demo.wx.miniapp.exception;

import cn.hutool.core.util.StrUtil;
import com.github.binarywang.demo.wx.miniapp.enums.ResponseCode;
import com.github.binarywang.demo.wx.miniapp.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlExceptionHandler {

    /**
     * 捕捉自定义异常
     *
     * @param RrException
     * @return
     */
    @ExceptionHandler(RrException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result globalException(RrException RrException) {
        log.error("globalException异常信息:{}", RrException.toString());
        String mess = StrUtil.isBlank(RrException.getMsg()) ? RrException.getMessage() : RrException.getMsg();
        return Result.error(RrException.getCode(), mess);
    }

    /**
     * 参数校验
     *
     * @param e
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public Result argumentNotValidException(Exception e, HttpServletRequest request) {
        //1.拿到绑定结果
        BindingResult bindingResult;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        } else {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }

        String message = wrapperBindingResult(bindingResult);
        log.error("参数校验异常:URI:{}----argumentNotValidException异常信息:{},", request.getRequestURI(), message);
        return Result.error(message);
    }

    /**
     * 验证请求时候的参数(该用法适用于方法所在的Controller上加注解@Validated,并且GET请求参数被JSR303修饰)
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @org.springframework.web.bind.annotation.ExceptionHandler(ConstraintViolationException.class)
    public Result handleServiceException(ConstraintViolationException e, HttpServletRequest request) {
        log.error("请求发生异常 ,参数验证失败,URL:{} ", request.getRequestURI());

        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder errorMessage = new StringBuilder();

        for (ConstraintViolation<?> constraintViolation : violations) {
            Path propertyPath = constraintViolation.getPropertyPath();//此时拿到的参数名称为:方法名:参数名,所以需要处理一下,只保留参数名
            String property = propertyPath.toString();
            property = property.substring(property.indexOf(".") + 1, property.length());
            String message = constraintViolation.getMessage();
            errorMessage.append(property).append("-").append(message).append(";");
        }
        return Result.error(errorMessage.toString());
    }


    /**
     * 缺少请求参数
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @org.springframework.web.bind.annotation.ExceptionHandler(MissingServletRequestParameterException.class)
    public Result handleMissingServletRequestParameterException(
        MissingServletRequestParameterException e, HttpServletRequest request) {
        log.error(request.getRequestURI() + ":缺少请求参数:" + e.getParameterName());
        return Result.error("缺少请求参数");
    }

    /**
     * 参数类型传递错误
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result falseRequestParameterException(
        MethodArgumentTypeMismatchException m, HttpServletRequest request) {
        log.error("参数类型错误 ,URL:{}", request.getRequestURI());
        return Result.error("参数类型错误");
    }

    /**
     * 请求方式错误
     *
     * @param m
     * @param request
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @org.springframework.web.bind.annotation.ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result falseRequestMethodException(
        HttpRequestMethodNotSupportedException m, HttpServletRequest request) {
        return Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), HttpStatus.METHOD_NOT_ALLOWED.getReasonPhrase());
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @org.springframework.web.bind.annotation.ExceptionHandler(HttpMessageNotReadableException.class)
    public Result handleHttpMessageNotReadableException(
        HttpMessageNotReadableException e, HttpServletRequest request) {
        log.error(request.getRequestURI() + ":参数解析失败", e);
        return Result.error(ResponseCode.ERROR.getCode(), "参数解析失败");
    }

    /**
     * 处理返回数据
     *
     * @param bindingResult
     * @return
     */
    private String wrapperBindingResult(BindingResult bindingResult) {
        // 默认赋值 参数异常
        StringBuilder errorMessage = new StringBuilder();
        // 获取所有校验出错的属性的默认提示语
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getField()).append("-").append(fieldError.getDefaultMessage()).append(";");
        }
        return errorMessage.toString();
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    public Result allException(Exception e, HttpServletRequest request) {
        e.printStackTrace();
        // 其他异常，当我们定义了多个异常时，这里可以增加判断和记录
        log.error("出现未知异常,URL:{} ,异常信息: {}", request.getRequestURI(), e);
        String message = ResponseCode.ERROR.getMessage();
        return Result.error(message);
    }


}
